package com.bnq.logc.task

import android.util.Log
import com.bnq.logc.LogcManager
import com.bnq.logc.db.LogcDao
import com.bnq.logc.upload.UploadFileManager
import com.bnq.logc.utils.DateUtil
import com.bnq.logc.utils.FileUtil
import com.bnq.logc.utils.StorageUtil
import java.io.File

class DeleteLogTask : LogTask() {
    override fun execute() {
        try{
            //先删除30{$mStorageDays}天前的log文件
            //FileUtil.deleteFilesOutDate(LogcManager.getConfig().getParentFileDir().absolutePath,LogcManager.getConfig().mStorageDays)
            val config = LogcManager.getConfig()
            val MAXFILEAGE = config.getStorageDayMillisecond()
            FileUtil.deleteFilesAction(config.getParentFileDir()){file ->
                val lastModified = file.lastModified()
                if (lastModified + MAXFILEAGE < System.currentTimeMillis() || isExpireFile(file)) {
                    logErrorDebug("本地删除了${config.mStorageDays}天以上的日志: ${file.absolutePath}")
                    return@deleteFilesAction true
                }
                false
            }
            //检查是否是低内存
            if(config.mLowMemoryByte > StorageUtil.getRomAvailableSize()){
                //获取上传结束的文件，除了本周的
                val uploadOverFiles = FileUtil.findFiles(config.getParentFileDir()){ file ->
                    !FileUtil.isWeekFile(file) && !FileUtil.isTodayFile(file) && isUploadOver(file)
                }
                //删除上传结束的
                uploadOverFiles.forEach { file ->
                    val success = file.delete()
                    logErrorDebug("本地删除了一周以上上传成功的日志:${success}: ${file.absolutePath}")
                }
            }
            //同步
            UploadFileManager.checkAndUploadFileLastCount(config.mStorageDays.toInt()){result->
                if(config.mLowMemoryByte > StorageUtil.getRomAvailableSize()){
                    //获取上传结束的文件，除了当天的
                    val uploadOverFiles = FileUtil.findFiles(config.getParentFileDir()){ file ->
                        !FileUtil.isTodayFile(file) && isUploadOver(file)
                    }
                    //删除上传结束的
                    uploadOverFiles.forEach { file ->
                        val success = file.delete()
                        logErrorDebug("本地删除了一天以上上传成功的日志:${success}: ${file.absolutePath}")
                    }
                }
            }
        }catch (e:Exception){
            e.printStackTrace()
            if(LogcManager.getConfig().mIsDebug){
                throw e
            }
        }
    }

    private fun logErrorDebug(message:String){
        if(LogcManager.getConfig().mIsDebug){
            Log.e("Logc",message)
        }
    }

    fun isUploadOver(file:File):Boolean{
        return LogcDao.querySingleByPath(file.absolutePath)?.let { fileInfo->
            fileInfo.fileLastUpdateSize >= file.length()
        }?:false
    }

    fun isExpireFile(file:File):Boolean{
        val date = FileUtil.getDateFromName(file)?:return false
        val days = DateUtil.getDiffDaysToNow(date)
        return days > LogcManager.getConfig().mStorageDays
    }
}